<script>
import _ from 'lodash'
import { getGroupInfoApi } from '@/API/home'
import { mapState, mapMutations } from 'vuex'
import { companyListApi } from '@/API/reqData'
import { carsRoCompanyList } from '@/API/testDrive'
import { changeUrl, setCentersList } from '@/utils/utils'
import { brand, brand_id } from '@/static/js/staticData'
export default {
  onShow(options) {
    // console.log('onShow-scene', options.query.scene)
    console.log('onShow-query', options.query)
    // console.log('onShow-scene', options.scene)
    if (options?.query?.scene) { // 判断是否存在公司id
      let param1 = decodeURIComponent(options?.query?.scene)
      let temp = changeUrl(param1)
      let { c } = temp
      if (c && c != 'null' && c != 'undefind') {
        console.log('scene-cc', c)
        this.saveComIndex(c)
      }
    }
    if (options?.query?.c) { // 判断是否存在公司id
      let { c } = options?.query
      if (c && c != 'null' && c != 'undefind') {
        console.log('query-cc', c)
        this.saveComIndex(c)
      }
    }

    let nowTime = Date.parse(new Date())
    let shareInfo = JSON.parse(uni.getStorageSync('shareInfo') || '{}')
    if (Object.keys(shareInfo).length) {
      let isTrue = nowTime > shareInfo.curTime + 60 * 60 * 24 * 1000
      if (isTrue) {//  超过时间，清空分享信息
        uni.setStorageSync('shareInfo', JSON.stringify({}))
      }
    }

    let path = 'Shop/GoodsDetail'
    if (options.path == path) {
      //商品详情进入
      // console.log('GoodsDetail',)
      let sceneArr1 = [1007, 1008, 1010, 1014, 1154, 1155]
      let sceneArr2 = [1011, 1012, 1013, 1047, 1048, 1049] //识别码进入
      let index1 = sceneArr1.indexOf(options.scene)
      let index2 = sceneArr2.indexOf(options.scene)
      if (index1 > -1) {
        if (options?.query?.p && options?.query?.p != 'null') {
          let { p: telphone } = options.query
          let shareInfo = {
            shareInfo: { telphone },
            curTime: nowTime
          }
          uni.setStorageSync('shareInfo', JSON.stringify(shareInfo))
        } else if (options?.query?.p && options?.query?.p == 'null') {
          uni.setStorageSync('shareInfo', JSON.stringify({}))
        }
      } else if (index2 > -1) { //识别码进入
        let param1 = decodeURIComponent(options?.query?.scene)
        let temp = changeUrl(param1)
        if (temp?.p && temp?.p != 'null') {
          let { p: telphone } = temp
          let shareInfo = {
            shareInfo: { telphone },
            curTime: nowTime
          }
          uni.setStorageSync('shareInfo', JSON.stringify(shareInfo))
        } else if (temp?.p && temp?.p == 'null') {
          uni.setStorageSync('shareInfo', JSON.stringify({}))
        }
      } else {
        // 清空分享信息
        uni.setStorageSync('shareInfo', JSON.stringify({}))
      }
    }
    // 超过24小时清空购物车
    let curTime = JSON.parse(uni.getStorageSync('curTime') || '{}')
    if (Object.keys(curTime).length) {
      // let isTrue = nowTime > curTime.curTime + 60 * 60 * 6 * 1000
      let isTrue = nowTime > curTime.curTime + 60 * 60 * 24 * 1000
      if (isTrue) {
        //  清空购物车
        this.emptyShoppCart()
      }
    } else {
      //  清空购物车
      this.emptyShoppCart()
    }
  },
  onLaunch(options) {
    this.saveUserNotLogin(false)
    // 获取品牌信息
    this.getGroupInfo()
    // 获取车型列表保存到vuex
    this.getCarsList()
    // 获取车型列表保存到vuex
    // this.getCompanyList()
    // this.getShopComList()
    let pathArr = ['pages/activity/share', 'pages/activity/share_activity']
    if (pathArr.includes(options.path)) {
      return false
    } else {
      // 获取定位
      // this.getLocation()
      this.getCompanyList()
    }
  },
  data() {
    return {
      latLog: {}
    }
  },
  methods: {
    // 获取车型列表保存到vuex
    async getCarsList() {
      let carSeri = []
      const {
        data: { data }
      } = await carsRoCompanyList({ brand, brand_id, state: 1 })
      // console.log('CRM', data.centers)
      // 车型
      let carSeris = data?.carSeris || []
      let centers = data?.centers || []
      carSeri = carSeris.map(item => ({
        value: item.modelName,
        text: item.modelName
      }))
      // 车型列表保存到vuex中
      this.saveCarSeris(carSeri)
      // 服务中心列表，用于券中心
      this.saveCentersList(centers)
    },
    // 获取服务中心和车型列表保存到vuex
    async getCompanyList() {
      const {
        data: { data }
      } = await companyListApi({
        state: 1,
        brand_id,
        company_type: 1,
      })
      let temp = data
        .map(item => {
          if (item.company_list.length > 0) {
            // console.log('item :>> ', item);
            let { id, company_id, company_name, crm_company_id } = item
            let { ev_on, latitude, longitude, sale_hotline, after_sales_hotline: hotline, markers_address: address, rescue_telephone, appointment_telephone, company_images } = item.company_list[0]
            return {
              id,
              ev_on,
              address,
              hotline,
              latitude,
              longitude,
              sale_hotline,
              crm_company_id,
              text: company_name,
              value: company_name,
              companyId: company_id,
              appointment_telephone,
              company_img: company_images,
              rescueTelephone: rescue_telephone,
            }
          }
        })
        .filter(Boolean)

      // 设置客服中心列表
      let { latitude, longitude, } = this.latLog
      if (latitude) {
        let temp2 = setCentersList(temp, longitude, latitude)
        this.saveCenters(temp2)
        uni.setStorageSync('oneCenters', JSON.stringify(temp2[0]))
      } else {
        this.saveCenters(temp)
        uni.setStorageSync('oneCenters', JSON.stringify(temp[0]))
      }
    },
    // 公司列表
    async getShopComList() {
      // 公司列表
      let param = {
        state: 1,
        brand_id,
        company_type: 1,
        goods_no: 1 //是否有商场
      }
      const {
        data: { data }
      } = await companyListApi(param)
      let temp = data
        .map(item => {
          if (item.company_list.length > 0) {
            let { id, company_name } = item
            let { latitude, longitude, markers_address } = item.company_list[0]
            return {
              id,
              latitude,
              longitude,
              value: id,
              company_name,
              distance: null,
              address: markers_address
            }
          }
        })

      let { latitude, longitude, } = this.latLog
      if (latitude) {
        let temp2 = setCentersList(temp, longitude, latitude)
        this.saveShopComList(temp2)
      } else {
        this.saveShopComList(temp)
      }
    },
    getLocation() {
      uni.getLocation({
        type: 'wgs84',
        success: res => {
          // console.log('纬度' + res.latitude)
          // console.log('经度' + res.longitude)
          let { latitude, longitude } = res
          let latLog = { latitude, longitude }
          this.latLog = latLog
          uni.setStorageSync('latLog', JSON.stringify(latLog))
          this.saveLatLog(latLog)
          // 获取服务中心
          this.getCompanyList()
          this.getShopComList()
        },
        fail: err => {
          this.getSetting()
        }
      })
    },
    // 1.获取设置信息-用户权限列表
    getSetting() {
      uni.getSetting({
        success: res => {
          // console.log('用户权限列表:', res.authSetting)
          if (res.authSetting['scope.userLocation']) {
            // 来到这里说明开启了授予位置权限而手机未开启定位功能
            uni.$showMsg(
              '您的手机未开启定位功能，为了更好地服务您，请开启手机定位。',
              2500
            )
            // 获取服务中心
            this.getCompanyList()
            this.getShopComList()
          } else {
            // console.log('用户未授权userLocation')
            //2.用户第一次进来发起授权
            uni.showModal({
              title: '授予位置权限',
              content:
                '为了更好的服务您，需要您的地理位置，请开启手机定位并授予位置权限',
              duration: 3000,
              success: res => {
                if (res.confirm) {
                  this.openSetting()
                } else if (res.cancel) {
                  uni.showToast({
                    title: '您未同意位置授权，无法向您提供位置信息服务！',
                    duration: 2000,
                    icon: 'none'
                  })
                  // 获取服务中心
                  this.getCompanyList()
                  this.getShopComList()
                }
              }
            })
          }
        }
      })
    },
    // 4.打开设置
    openSetting() {
      uni.openSetting({
        success: res => {
          if (res.authSetting['scope.userLocation']) {
            // 5.用户在设置中点击了允许，调用选择位置信息函数
            this.getLocation()
          } else {
            // 5.用户在设置中点击了不允许，展示拒绝授权信息
            // 获取服务中心
            this.getCompanyList()
            this.getShopComList()
            uni.showToast({
              title: '您未同意位置授权，无法向您提供位置信息服务！',
              icon: 'none',
              duration: 3000
            })
          }
        },
        fail: err => {
          console.log('打开设置失败', err)
        }
      })
    },
    // 公司与品牌信息
    async getGroupInfo() {
      const {
        data: { data }
      } = await getGroupInfoApi({ id: brand_id })
      let temp = data.brandInfo.map(item => ({
        brand_id,
        info: item.info,
        video_url: item.video_url,
        logoUlr: item.brand_images,
      }))
      this.saveGroupInfo(temp)
    },
    ...mapMutations([
      'saveLatLog',
      'saveComIndex',
      'saveCarSeris',
      'saveCenters',
      'saveGroupInfo',
      'emptyShoppCart',
      'saveShareInfo',
      // "saveSystem",
      'saveCentersList',
      'saveShopComList',
      'saveUserNotLogin',
      // 'saveOnOff',
      // 'savePathLink'
    ])
  },
  computed: {
    ...mapState(['pathLink']),
  },
  globalData: {}
}
</script>

<style lang="scss">
@import '@/uni_modules/uview-ui/index.scss';
@import './styles/ZeekrText-Regular.css'; // Zeekr字体，2024.1.29

@import './styles/iconfont.css'; //字体图标
/*每个页面公共css */
@import './styles/base.scss';

@font-face {
  font-family: 'iconfont';
  src: url('//at.alicdn.com/t/c/font_1711657_dbbpwooxn.woff2?t=1676966961316') format('woff2'),
    url('//at.alicdn.com/t/c/font_1711657_dbbpwooxn.woff?t=1676966961316') format('woff'),
    url('//at.alicdn.com/t/c/font_1711657_dbbpwooxn.ttf?t=1676966961316') format('truetype');
}

.iconfont {
  font-family: 'iconfont' !important;
  font-size: 58rpx;
  font-style: normal;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

page {
  height: 100%;
}
</style>
